import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as { name: string; email: string } | null,
  }),
  getters: {
    getUser: (state) => state.user,
    isAuthenticated: (state) => !!state.user,
  },
  actions: {
    setUser(newUser: { name: string; email: string }) {
      this.user = newUser;
      // 将用户信息存储到 sessionStorage
      sessionStorage.setItem('user', JSON.stringify(newUser));
    },
    logout() {
      this.user = null;
      // 从 sessionStorage 中移除用户信息
      sessionStorage.removeItem('user');
      // 跳转到根路径
    },
    // 在应用启动时从 sessionStorage 恢复用户信息
    initUser() {
      const userData = sessionStorage.getItem('user');
      if (userData) {
        this.user = JSON.parse(userData);
      }
    },
  },
});